package com.bwie.task;

import cn.hutool.core.bean.BeanUtil;
import com.bwie.Es.EsGoods;
import com.bwie.Es.EsImages;
import com.bwie.pojo.Goods;
import com.bwie.pojo.Image;
import com.bwie.service.GoodsService;
import com.bwie.service.ImageService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class GoodsTask {


    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private ImageService imageService;

    @Scheduled(cron = "0/30 * * * * ?")
    public void task() {
        System.out.println("开启同步");
        List<Goods> list = goodsService.list1();
        List<Image> images = imageService.list();
        for (Goods goods : list) {
            List<Image> arrayList = new ArrayList<>();
            for (Image image : images) {
                if (goods.getId() == image.getGoodsId()) {
                    arrayList.add(image);
                }
            }
            goods.setImageList(arrayList);
            EsGoods esGoods = BeanUtil.toBean(goods, EsGoods.class);
            elasticsearchRestTemplate.save(esGoods);
        }
        System.out.println("关闭同步");
    }
}
